package com.coder4j.starter.web.jwt;

import com.coder4j.starter.tools.util.StringUtils;
import com.coder4j.starter.tools.vo.BaseException;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Token工具类
 * @author Keller
 * @date 2023-02-21 20:06:00
 */
public class TokenUtils {

    public static final String header = "Authorization";

    private static final String key = "YWJj5L2g5aW95ZWK77yBQUJDIUAjJCVeJio";

    /**
     * 构建Token
     * @param vo
     * @return
     */
    public static String buildToken(AuthVO vo){
        JWTHeader header = new JWTHeader();
        header.setId(vo.getUserId() + "");
        header.setTo(vo.getUserName());

        Map<String,String> map = new HashMap<>();
        if(vo.getCustomData() != null){
            map = vo.getCustomData();
        }

        try {
            return JWTUtils.getCustomToken(key,header,map);
        } catch (TokenException e) {
            e.printStackTrace();
            throw BaseException.error("Token构造失败");
        }
    }

    public static Long getUserId(HttpServletRequest request){
        String token = request.getHeader(TokenUtils.header);
        if(StringUtils.isEmpty(token)){
            return null;
        }
        return getUserId(token);
    }

    public static Long getUserId(String token){
        try {
            JWT jwt = JWTUtils.parseToken(token, key);
            return Long.parseLong(jwt.getHeader().getId());
        } catch (TokenException e) {
            e.printStackTrace();
            throw BaseException.error("Token解析失败");
        }
    }

    public static void main(String[] args) {
        AuthVO vo = new AuthVO();
        vo.setUserId(10010L);
        vo.setUserName("keller");

        String token = buildToken(vo);
        System.out.println(token);

    }
}
